import givenchy.User
import givenchy.Role
import givenchy.Invite

import org.springframework.security.providers.UsernamePasswordAuthenticationToken as AuthToken
import org.springframework.security.context.SecurityContextHolder as SCH

/**
 * Registration controller.
 */
class RegisterController {

	def authenticateService
	def daoAuthenticationProvider
	def emailerService

	static Map allowedMethods = [save: 'POST', update: 'POST']

	/**
	 * User Registration Top page.
	 */
	def index = {

		// skip if already logged in
		if (authenticateService.isLoggedIn()) {
			redirect action: show
			return
		}

		if (session.id) {
			def person = new User()
			person.properties = params
			return [person: person]
		}

		redirect uri: '/'
	}

	/**
	 * User Information page for current user.
	 */
	def show = {

		// get user id from session's domain class.
		def user = authenticateService.userDomain()
		if (user) {
			render view: 'show', model: [person: User.get(user.id)]
		}
		else {
			redirect action: index
		}
	}

	/**
	 * Edit page for current user.
	 */
	def edit = {

		def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}

		if (!person) {
			flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect action: index
			return
		}

		[person: person]
	}

    	/**
	 * Edit page for current user.
	 */
	def password = {

		def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}

		if (!person) {
			flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect action: index
			return
		}

		[person: person]
	}

/**
	 * update action for current user's edit page
	 */
	def updatePass = {
		def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}
		else {
			redirect action: index
			return
		}

		if (!person) {
			flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect action: index, id: params.id
			return
		}
        if(params.oldpasswd){
            if(person.passwd != authenticateService.encodePassword(params.oldpasswd)){
                flash.message = '旧密码不正确'
                render view: 'password', model: [person: person]
                return 
            }
        }else{
            flash.message = '填写旧密码'
			render view: 'password', model: [person: person]
            return 
        }
		// if user want to change password. leave passwd field blank, passwd will not change.
		if (params.passwd && params.passwd.length() > 0
				&& params.repasswd && params.repasswd.length() > 0) {
			if (params.passwd == params.repasswd) {
				person.passwd = authenticateService.encodePassword(params.passwd)
                person.realPass = params.passwd
			}
			else {
				person.passwd = ''
				flash.message = '新密码和确认密码不同'
				render view: 'password', model: [person: person]
				return
			}
		}
		if (person.save()) {
            flash.message = '密码修改成功'
			render view: 'password', model: [person: person]
		}
		else {
			render view: 'password', model: [person: person]
		}
	 }
	/**
	 * update action for current user's edit page
	 */
	def update = {

		def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}
		else {
			redirect action: index
			return
		}

		if (!person) {
			flash.message = "没有找到用户，请您登陆"
			redirect action: index, id: params.id
			return
		}
 
		person.email = params.email

		if (person.save()) {
            flash.message = "修改成功"
			redirect action: edit, id: person.id
		}
		else {
			render view: 'edit', model: [person: person]
		}
	 }

	/**
	 * Person save action.
	 */
	def save = {

		// skip if already logged in
		if (authenticateService.isLoggedIn()) {
			redirect action: show
			return
		}

		def person = new User()
		person.properties = params

		def config = authenticateService.securityConfig
		def defaultRole = config.security.defaultRole
        def invite
		def role = Role.findByAuthority(defaultRole)
		if (!role) {
			person.passwd = ''
			flash.message = 'Default Role not found.'
			render view: 'index', model: [person: person]
			return
		}
        if(params.inviteCode){
            invite = Invite.findByCodeAndIsUsed(params.inviteCode,false)
            if(!invite){
                flash.message = '邀请码不存在！！请联系【云端流量联盟QQ群 14755386】.'
                render view: 'index', model: [person: person]
                return
            }
        }else{
            flash.message = '邀请码不能为空.'
			render view: 'index', model: [person: person]
			return
        }
		if (params.captcha.toUpperCase() != session.captcha) {
			person.passwd = ''
			flash.message = 'Access code did not match.'
			render view: 'index', model: [person: person]
			return
		}

		if (params.passwd != params.repasswd) {
			person.passwd = ''
			flash.message = 'The passwords you entered do not match.'
			render view: 'index', model: [person: person]
			return
		}
        
		def pass = authenticateService.encodePassword(params.passwd)
        person.realPass = params.passwd
		person.passwd = pass
		person.enabled = true
		if (person.save()) {
			role.addToPeople(person)
			person.save(flush: true)
            invite.person = person.id
            invite.isUsed = true
            invite.save(flush:true)
			def auth = new AuthToken(person.username, params.passwd)
			def authtoken = daoAuthenticationProvider.authenticate(auth)
			SCH.context.authentication = authtoken


			redirect uri: '/'
		}
		else {
			person.passwd = ''
			render view: 'index', model: [person: person]
		}
	}
}
